define(window.backboneCommon.getViewDefine("spread.list"), function ($,require,Collection,tpl,ViewDetail) {
    var defaultsOptions={
        campaignId:"",
        jumpOutsideCallback:null,
        refreshCallback:null
    };
    var pagePrivate = {
        getDefaults :function () {
            return defaultsOptions
        },
        getOptions : function (options) {
            options=$.ExtCommon.isCheckEmpty(options)?{}:options;
            return $.ExtCommon.initMergeJson(this.getDefaults(),options);
        }
    };
    var backboneView= Backbone.View.extend({
        events: {
            "click #btn_addSpread ": "addSpread",
            "click #tb_spreadList .edit-spread": "editSpread",
            "click #tb_spreadList .jump-outside": "jumpOutside"
        },
        initialize: function () {
            this.listenTo(this.model, "bind:PageList", this.bindList);
            this.listenTo(this.model, "update:Status", this.updStatusCallback);
            this.listenTo(this.model, "update:Price", this.updPriceCallback);
            this.render();
        },
        render:function(){
            var templateHtml=_.template(tpl);
            this.$el.html(templateHtml());
            return this;
        },
        initMain:function(options){
            this.elementModel={
                table:$("#tb_spreadList")
            };
            this.extObject={};
            this.pageData={initPage:false};
            this.pageData.operateStatus=this.model.get("defOperateStatus");
            this.pageOptions=$.ExtCommon.initMergeJson(pagePrivate.getOptions(),options);
            this._initInputSearch();
            this._initTimeRange();
        },
        initPage:function(param){
            var currentTime=this.getTimeRangeValue();
            var isChange=param.startTime!==currentTime.startTime || param.endTime!==currentTime.endTime;
            if(isChange){this.extObject.timeRange.setValue(param.startTime,param.endTime)}
            if(!this.pageData.initPage){
                this.pageData.initPage=true;
                this.initViewAttach();
                this._initPageList();
            }else{
                if(isChange){this.refreshList()}
            }
        },
        initViewAttach:function () {
            var self=this;
            this.viewAttach={};
            this.viewAttach.detail=new ViewDetail({pElement:"#container_spreadDetails",campaignId:this.pageOptions.campaignId,
                submitCallback: function (isAdd, json) {
                    if(isAdd){
                        self.refreshList();
                    }else{
                        var tr=$("#spread_"+json.id).parent();
                        var row = self.extObject.table.getRowInfo(tr);
                        var originalData=row.data();
                        var elementTd=$('td', tr);
                        if(json.name!==originalData.name){
                            $("#btn_spread_"+json.id).text(json.name);
                            row.data()["name"]=json.name;
                        }
                        if(json.dayBudget.toString()!==originalData.unitPrice.toString()){
                            json.unitPrice=json.dayBudget;
                            self._bindPrice(elementTd.eq(3),json);
                            row.data()["unitPrice"]=json.dayBudget;
                        }
                        $.ExtNumeric.initAll();
                        self._initXEditable();
                    }
                    if(self.pageOptions.refreshCallback()){self.pageOptions.refreshCallback()}
                }
            });
        },
        _initInputSearch:function () {
            var self=this;
            self.extObject.inputSearch=$("#panel_inputSearch_spread").ExtInputSearch({
                placeholder:"计划ID,计划名称",
                searchCallback:function () {
                    self.refreshList();
                }
            })
        },
        _initTimeRange:function () {
            var self=this;
            self.extObject.timeRange=$("#search_spreadTimeRange").ExtDatePicker({type:"range",
                addQuick:{"本月": [$.ExtMoment.initMoment().startOf('month'), $.ExtMoment.initMoment()]},
                maxDate:$.ExtMoment.initMoment(),
                startValue:$.ExtMoment.initFormat(),endValue:$.ExtMoment.initFormat(),
                changeCallback: function () {self.refreshList()}
            });
        },
        getTimeRangeValue:function(){
            var arrTime =this.extObject.timeRange.getValue();
            return {startTime:arrTime[0],endTime:arrTime[1]}
        },

        _initPageList: function () {
            var self=this;
            self.extObject.table=self.elementModel.table.ExtDataTable({
                columns: [
                    {data: "id", class: "w-60"},
                    {data: "name", class: "p-r-20"},
                    {data: "statusName",class: "w-50 text-center"},
                    {data: "unitPrice", class: "w-80"},
                    {data: "strategyCount", class: "w-70"},
                    {data: "creativeCount", class: "w-70"},
                    {data: "pv",class: "w-85 text-right num-int"},
                    {data: "click",class: "w-85 text-right num-int"},
                    {data: "cr", class: "w-85 text-right num-float2"},
                    {data: "price", class: "w-85 text-right num-float2"},
                    {data: "cost",class: "w-110 text-right num-float2"}
                ],
                infoExt:{
                    ajaxDataPara:function(){
                        var param= {};
                        param.campaignId=self.pageOptions.campaignId;
                        var keyword = self.extObject.inputSearch.getValue();
                        if (!$.ExtCommon.isCheckEmpty(keyword)) {param.search = keyword;}
                        var timeRange=self.getTimeRangeValue();
                        param= $.ExtCommon.initMergeJson(param,timeRange);
                        return param;
                    },
                    ajaxWholeCallback:function(param){self.collection.getPageList(param)}
                },
                createdRow: function (row, data) {
                    data.campaignId=self.pageOptions.campaignId;
                    var elementTd=$("td", row);
                    elementTd.eq(1).attr("id","spread_"+data.id).html( $("#template_table_spread_name").render(data));

                    var tempJsonStatus = self._bindTableColumnByStatus(data.status);
                    elementTd.eq(2).html($.ExtCommon.getStringConnect(
                        '<a id="btn_spread_status_{0}" class="editable editable-click editable-init"  data-operate-type="status" href="javascript:">{1}</a>',
                        [data.id,data.statusName]
                    ));
                    elementTd.eq(2).find(".editable").data({list: tempJsonStatus.list});

                    self._bindPrice(elementTd.eq(3),data);

                    elementTd.eq(4).html($.ExtCommon.getStringConnect(data.strategyCount===0?'<span>{0}个策略</span>':'<a class="btn-operate longterm jump-outside" data-type="strategy"  href="javascript:">{0}个策略</a>',[data.strategyCount]));
                    elementTd.eq(5).html($.ExtCommon.getStringConnect(data.creativeCount===0?'<span>{0}个创意</span>':'<a class="btn-operate longterm jump-outside" data-type="creative"  href="javascript:">{0}个创意</a>',[data.creativeCount]));
                },
                drawCallback: function () {
                    $.ExtNumeric.initAll();
                    self._initXEditable();
                    $.ExtAssist.urlParam.setUrl(self.elementModel.table.find("a"));
                }
            });
        },
        bindList:function(){
            var data=this.model.get("dataPageList");
            this.extObject.table.ajaxWholeRefreshData(data);
        },
        refreshList: function () {this.extObject.table.refresh()},

        _bindPrice:function (el,json) {
            if(json.isWeChat){
                el.html("--")
            }else{
                el.html($.ExtCommon.getStringConnect(
                    '<a id="btn_spread_price_{0}" class="editable editable-click editable-init d-inline-block h-20" data-operate-type="price"  href="javascript:"><span class="num-int">{1}</span></a>',
                    [json.id,json.unitPrice]
                ));
            }
        },
        _bindTableColumnByStatus: function (status) {
            status=$.ExtCommon.isCheckUndefined(status)?"":status.toString();
            var list=$.map(this.pageData.operateStatus,function (info) {
                if(info.showIds.indexOf(status)>-1){
                    return {value:info.id,text:info.name}
                }
            });
            return {status: status, list: list}
        },
        _initXEditable: function () {
            var self=this;
            self.elementModel.table.find(".editable-click.editable-init").each(function () {
                var _this = $(this);
                _this.removeClass("editable-init");
                var _thisData = _this.data();
                var tr = $(this).parents("tr:first");
                var row =self.extObject.table.getRowInfo(tr);
                var rowData=row.data();
                var operateType = _thisData["operateType"];
                switch(operateType){
                    case "status":
                        _this.ExtXEditable({
                            source: _thisData.list,
                            type: "select",
                            params: function (params) {
                                var newParams= {};
                                newParams.id=rowData.id;
                                newParams.campaignId=self.pageOptions.campaignId;
                                newParams.status=$.trim(params.value);
                                return newParams;
                            },
                            infoExt:{
                                initControlOther: function () {
                                    _this.siblings(".editable-container").find("select").ExtSelect2({infoExt: {initValue: _thisData.list[0].value}});
                                },
                                ajaxWholeCallback:function (param) {
                                    $.ExtNotify.destroy();
                                    self.collection.updateStatus(param);
                                },
                                successCallback: function (res) {
                                    if(res.success){
                                        var tempJsonStatus = self._bindTableColumnByStatus(res.data.status);
                                        _this.text(res.data.statusName).data("list", tempJsonStatus.list);
                                        _this.ExtXEditable().refresh(tempJsonStatus.list);
                                        row.data().status = res.data.status;
                                        row.data().statusName = res.data.statusName;
                                    }
                                }
                            }
                        });
                        break;
                    case "price":
                        _this.ExtXEditable({
                            type: "text",
                            params: function (params) {
                                var newParams = {};
                                newParams.id=rowData.id;
                                newParams.campaignId=self.pageOptions.campaignId;
                                newParams.unitPrice =parseFloat($.trim(params.value).removesplit());
                                return newParams;
                            },
                            infoExt: {
                                validateExt: function (strValue) {
                                    var msg = "";
                                    var value=parseFloat(strValue);
                                    if (value <50||value>4000000) {
                                        msg = "输入值应该在 50 到 4000000 之间"
                                    }
                                    return msg
                                },
                                initControlOther: function () {
                                    $(".editable-container :text").ExtNumeric({numType:"int","vMax": 4000000});
                                },
                                ajaxWholeCallback:function (param) {
                                    $.ExtNotify.destroy();
                                    self.collection.updatePrice(param);
                                },
                                successCallback: function (res, newValue) {
                                    row.data().price = newValue.removesplit();
                                }
                            }
                        });
                        break;
                }
            });
        },
        updStatusCallback:function () {
            var result=this.model.get("dataUpdStatus");
            $("#btn_spread_status_"+result.req.id).ExtXEditable().ajaxWholeData(result.res);
        },
        updPriceCallback:function () {
            var result=this.model.get("dataUpdPrice");
            $("#btn_spread_price_"+result.req.id).ExtXEditable().ajaxWholeData(result.res);
        },

        addSpread:function () {
            this._showModal();
        },
        editSpread:function (e) {
            this._showModal($(e.currentTarget).data("id"));
        },
        _showModal:function (id) {
            this.viewAttach.detail.init(id);
        },

        jumpOutside:function (e) {
            var el=$(e.currentTarget);
            var tr = el.parents('tr:first');
            var rowData = this.extObject.table.getRowInfo(tr).data();
            var type=el.data("type");
            var param = $.ExtCommon.initMergeJson({spreadId:rowData.id},this.getTimeRangeValue());
            if(this.pageOptions.jumpOutsideCallback){this.pageOptions.jumpOutsideCallback(type,param);}
        }
    });
    var viewModel=function(options){
        this.collection= new Collection();
        this.model=this.collection.model;
        this.view=new backboneView({el:options.pElement,collection:this.collection,model:this.model});
        this.view.initMain(options);
    };
    viewModel.prototype={
        init:function (param) {
            this.view.initPage(param);
        },
        getTimeValue:function () {
            return this.view.getTimeRangeValue();
        }
    };
    return viewModel;
});